<template>
  <div class="addUser">
    <el-form v-loading="loadings" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="用户名:" prop="userName">
        <el-input class="ipts" ref="userName" size="small" maxlength="20" clearable v-model="ruleForm.userName" placeholder="请输入用户名"></el-input>
        <span>注:默认用户名为系统登录账号</span>
      </el-form-item>
      <el-form-item label="姓名:" prop="name">
        <el-input class="ipts" size="small" maxlength="20" clearable v-model="ruleForm.name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="手机号:" prop="phone">
        <el-input class="ipts" size="small" maxlength="11" onkeyup="value=value.replace(/[^\d]/g,'')" clearable v-model.number="ruleForm.phone" placeholder="请输入手机号"></el-input>
        <span>注:默认手机号为初始密码</span>
      </el-form-item>
      <el-form-item label="分组:" prop="group">
        <el-select class="ipts" size="small" @change="selectGroup" v-model="ruleForm.group" >
          <li id="newGroup" style="color: #409EFF; cursor: pointer;line-height:30px;font-size:14px;text-indent: 8px;" @click="addGroup">+ 新增分组</li>
          <el-option
            v-for="item in groupList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="角色:" prop="role">
        <el-select multiple clearable class="roleSelect" size="small" v-model="ruleForm.role" >
          <el-option
            v-for="item in roleList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <span>注:可多选</span>
      </el-form-item>
      <el-form-item label="状态:" prop="status">
        <el-radio-group v-model="ruleForm.status">
          <el-radio :label="0">启用</el-radio>
          <el-radio :label="1">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item >
        <el-col :span="20" style="text-align:right;" >
          <el-button type="primary" size="small" @click="submitForm('ruleForm')">提交</el-button>
          <el-button type="default" size="small" @click="resetForm('ruleForm')">返回</el-button>
        </el-col>
      </el-form-item>
      <el-form-item class="formDialog" >
        <el-dialog
          v-loading="loading"
          title="设置分组"
          :visible.sync="vilable"
          width="45%"
          :close-on-click-modal="false"
          :before-close="close"
        >
        <el-form-item label="分组名称:" prop="groupName">
          <el-input class="ipts" size="small" maxlength="20" clearable v-model="ruleForm.groupName" placeholder="请输入分组名称"></el-input>
        </el-form-item>
        <el-form-item class="centerGroup" label="分组描述:" prop="describe">
          <el-input class="ipts" type="textarea" maxlength="100" resize="none" :rows="5" size="small" clearable v-model="ruleForm.describe" placeholder="请输入分组名称"></el-input>
        </el-form-item>
        <el-form-item >
        <el-col :span="22" style="text-align:right;" >
          <el-button type="primary" size="small" @click="doSubit('ruleForm')">提交</el-button>
          <el-button type="default" size="small" @click="cancle('ruleForm')">取消</el-button>
        </el-col>
      </el-form-item>
        </el-dialog>
      </el-form-item>

    </el-form>
  </div>
</template>

<script>
import systemApi from "@/api/lejv/system"
// import Base64 from "@/utils/base64.min.js"
import md5 from "blueimp-md5"
import _ from "lodash"; //引入lodash
export default {
  name: "addUser",
  data() {
     // 校验手机号
    let validPhone = (rule, value, callback) => {
      if (value) {
        const reg = /^1[2|3|4|5|7|8|9][0-9]\d{8}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的手机号'))
        }
      }else{
        callback()
      }
    };
    let checkUserName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入用户名'));
      }else if(!this.isUserNameRight){
        return callback(new Error('已存在该用户名'));
      }else{
        callback();
      }
      
    };
    return {
      loading:false,
      loadings:false,
      isUserNameRight:true,
      ruleForm: {
        groupName:"",
        describe:"",
        userName:"",
        name: '',
        phone: '',
        group: '',
        role: [],
        password:"",
        status: 0,
      },
      vilable:false,
      rules: {
          groupName: [
            { required: true, message: '请输入分组名称', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
          userName: [
            // { required: true, message: '请输入用户名', trigger: 'blur' },
            { required: true,validator: checkUserName, trigger: 'blur' }
          ],
          phone: [
            {required: true,  message: '请输入手机号'},
            { validator: validPhone, trigger: 'blur'},
          ],
          group: [
            { required: true, message: '请选择分组', trigger: 'change' }
          ],
          role: [
            { type: 'array', required: true, message: '请选择角色', trigger: 'change' }
          ],
      },
      groupList:[],
      roleList:[]
    };
  },
  computed: {},
  created() { 
    if(this.$store.state.app.groupList.length == 0){ //因为数据有分页 可以使用下拉框懒加载进行分页请求 目前没实现
      this.getGroupList()
    }else{
      this.groupList = this.$store.state.app.groupList
    }
    if(this.$store.state.app.roleList.length <= 10){  //因为数据有分页 可以使用下拉框懒加载进行分页请求 目前没实现
      this.getRoleList()
    }else{
      this.roleList = this.$store.state.app.roleList
    }
    if(this.$route.params.id){
      this.getDetail(this.$route.params.id)
    }
  },
  mounted() {},
  methods: {
    //新增分组
    addGroup(){
      let newGroup = document.getElementById("newGroup")
      // console.log(12,newGroup);
      newGroup.style.backgroundColor = "#E0E0E0"
      setTimeout(()=>{
        newGroup.style.backgroundColor = "white"
      },200)
      this.ruleForm.groupName = ""
      this.vilable = !this.vilable
    },
    //提交分组
    doSubit(formName){
     if(this.ruleForm.groupName == ""){
       this.$refs.ruleForm.validateField('groupName');
     }else{
       this.loading = true
       let params = {
         name:this.ruleForm.groupName,
         describe: this.ruleForm.describe
       }
       systemApi.increaseGroup(params)
       .then(res=>{
         if(res.code == 0){
           this.$message({
             type:"success",
             message:"成功创建分组"
           })
           this.getGroupList()
           this.close()
           this.loading = false
         }else{
           this.loading = false
           this.$message({
             type:"warning",
             message: res.msg
           })
         }
       })
       .catch(res=>{
         this.loading = false
         this.$message({
           type:"error",
           message:"创建分组失败"
         })
       })
     }
    },
    //取消新增分组
    cancle(formName){
      this.close()
      this.$nextTick(()=>{
        this.$refs.ruleForm.clearValidate(this.ruleForm.groupName)
        setTimeout(()=>{
          this.ruleForm.groupName = "1"  //避免表单校验 (弹窗新增分组功能)
        },200)
      })
    },
    //自定义事件关闭弹窗
    close(){
      this.vilable = !this.vilable
      this.ruleForm.groupName = "",
      this.ruleForm.describe = ""
    },
    //选择分组
    selectGroup(val){
      // console.log(val);
      this.$refs.ruleForm.validateField('group');
      this.$forceUpdate()
    },
    //提交
    submitForm(formName) {
      this.$refs.ruleForm.validate((valid) => {
        // console.log(valid)
        if (valid) {
          this.loadings = true
          // alert('submit!');
          let item = {
            ...this.ruleForm
          }
          let api = null
          item.password = md5(item.phone)
          delete item.groupName
          delete item.describe
          item.role = item.role.join(",")
          if(this.$route.params.id){
            api = systemApi.updateUser
            item.groupCode = item.group
            delete item.group
            delete item.password
          }else{
            delete item.id
            api = systemApi.addUser
          }
          api(item)
          .then(res=>{
            if(res.code == 0){
              this.loadings = false
              if(this.$route.params.id){
                this.$message({
                  type:"success",
                  message:"提交成功"
                })
              }else{
                this.$message({
                  type:"success",
                  message:"成功创建用户"
                })
              }
              this.$router.push("/system/userManner")
            }else if(res.code == 14500){
              this.isUserNameRight = false
              this.$refs.ruleForm.validateField('userName')
              this.loadings = false
              this.$refs.userName.focus()
              setTimeout(()=>{
                this.$refs.ruleForm.clearValidate('userName')
                this.isUserNameRight = true
              },2000)
            }else{
              this.$message({
                type:"warning",
                message:res.msg
              })
              this.loadings = false
            }
          })
          .catch(res=>{
            this.loadings = false
            this.$message({
              type:"error",
              message:"创建用户失败"
            })
          })
        } else {
          this.loadings = false
          return false;
        }
      });
    },
    //返回
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$router.push("/system/userManner")
    },
    //获取编辑信息
    getDetail(id){
      this.loadings = true
      systemApi.getUserDetail({id})
      .then(res=>{
        if(res.code == 0){
          this.ruleForm = {...res.data.user[0]}
          this.ruleForm.status = Number(this.ruleForm.status)
          let items = this.groupList.find(item=>item.label == this.ruleForm.groupName)
          if(items){
            this.ruleForm.group = items.value
          }
          this.ruleForm.role = this.ruleForm.role.split(",")
          // console.log(this.ruleForm);
          
          for(let i = 0;i<this.ruleForm.role.length;i++){
            let item = this.roleList.find(item => item.label == this.ruleForm.role[i])
            if(item){
              this.ruleForm.role[i] = item.value
            }
          }
          this.ruleForm.groupName = ""
          this.loadings = false
          // console.log('23',this.ruleForm);
        }else{
          this.$message({
            type:"warning",
            message: res.msg
          })
          this.loadings = false
        }
      })
      .catch(res=>{
        // console.log(res);
        this.$message({
          type:"error",
          message:"获取用户数据失败"
        })
        this.loadings = false
      })
    },
    //获取分组列表
    async getGroupList(){
      let params = {
        pageSize:999,
        pageNum:1
      }
      await systemApi.getGroupList(params)
      .then(res=>{
        // console.log(res,11);
        if(res.code == 0){
          this.groupList = res.data.groups.map(item => {
            return {
              label: item.name,
              value: item.id
            }
          })
          this.$store.state.app.groupList = this.groupList
        }
      })
      .catch(res=>{
        this.$message({
          type:"error",
          message:"获取分组数据失败"
        })
      })
    },
    //获取角色列表
    async getRoleList(){
      let params = {
        pageSize:999,
        pageNum:1
      }
      await systemApi.getRoleList(params)
      .then(res=>{
        // console.log(res);
        if(res.code == 0){
          this.roleList = res.data.roles.map(item => {
            return {
              label: item.name,
              value: item.id
            }
          })
          this.$store.state.app.roleList = this.roleList
        }
      })
      .catch(res=>{
        this.$message({
          type:"error",
          message:"获取角色列表失败"
        })
      })
    }
  }
};
</script>
<style scoped lang="scss">
.addUser {
  margin: 30px 10px;
  ::v-deep.formDialog{
    .el-loading-mask {
      z-index: 90;
      // width: 46%;
      // left: 27%;
      background-color: rgba(255,255,255,.5);
    }
    // .el-loading-spinner{
    //   width: 50%;
    // }
    .el-dialog{
      height: 340px;
    }
    .centerGroup{
      margin: 20px 0;
    }
    .ipts{
      width: 90%;
    }
    .el-dialog__header{
      border-bottom: 1px solid #E0E0E0;
    }
    .el-dialog__body{
      padding: 20px 0!important;
    }
  }
  .ipts{
    width: 300px;
  }
  .roleSelect{
    width: 400px;
  }
  span{
    margin-left: 10px;
    color: #BBBBBB;
    font-size: 12px;
  }
  
}
</style>
